<?php
/*
 * @Description    : 个人设置
 * @Version        : 1.0.0
 * @Author         : QianLong
 * @Date           : 2021-05-05 11:03:26
 * @LastEditors    : QianLong
 * @LastEditTime   : 2023-10-28 17:25:03
 */

namespace app\api\controller;

use app\common\model\Manager;
use app\common\model\SysSetting;
use app\common\service\Wwork;
use app\lib\exception\ApiException;
use app\lib\Result;
use think\facade\Validate;
use Yurun\Util\HttpRequest;

class Personal extends Base
{
  public function security_setting()
  {
    $user['phone']    = $this->user['phone'];
    $user['email']    = $this->user['email'];
    return Result::Success($user);
  }
  public function binding_account()
  {
    $user['wechat_nickname']    = $this->user['wechat_open_id'];
    $user['ww_user_bind']    = (!empty($this->user['ww_user_id'])) ? 1 : 0;
    // $setting = SysSetting::where('id', 1)->find();
    // if (!empty($setting['wechat_appid']) && !empty($setting['wechat_secret'])) {
    //   $user['wechat_oauth'] = 1;
    //   $user['wechat_appid'] = $setting['wechat_appid'];
    // }
    // if (!empty($setting['ww_appid']) && !empty($setting['ww_agentid'])) {
    //   $user['ww_oauth'] = 1;
    //   $user['ww_appid'] = $setting['ww_appid'];
    //   $user['ww_agentid'] = $setting['ww_agentid'];
    // }
    return Result::Success($user);
  }
  public function change_pwd()
  {
    if (request()->isPost()) {
      $rule = [
        'password|密码' => 'require|min:8|max:26',
        'new_password|新密码' => 'require|min:8|max:26',
      ];
      $data = [
        'password'  => input('param.password/s', '', 'trim'),
        'new_password'  => input('param.new_password/s', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Error($validate->getError());
      }
      $hasUser = Manager::field('salt,password,status')->where('id', $this->uid)->find();
      if (empty($hasUser)) {
        return Result::Error('登录已过期，请重新登录', -2);
      }
      if ($hasUser['status'] != 1) {
        return Result::Error('用户状态异常或被封禁，请联系上级管理进行处理。');
      }
      $saltPassword = md5($data['password'] . $hasUser['salt']);
      if ($saltPassword != $hasUser['password']) {
        return Result::Error('原密码不正确，请确认后重新输入');
      }
      $update['salt'] = make_salt();
      $update['password'] = md5($data['new_password'] . $update['salt']);
      Manager::where('id', $this->uid)->update($update);
      return Result::Success();
    }
    return Result::Error('请求不正常');
  }
  public function change_phone()
  {
    if (request()->isPost()) {
      $rule = [
        'phone|手机号' => 'require|mobile',
        'captcha|验证码' => 'require|min:4|max:6',
        'current' => 'require',
      ];
      $data = [
        'phone'  => input('param.phone', '', 'trim'),
        'captcha'  => input('param.captcha', '', 'trim'),
        'current'  => input('param.current', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Error($validate->getError());
      }
      $hasUser = Manager::field('id')->where('phone', $data['phone'])->find();
      if ($data['current'] == 'change_phone_old' && empty($hasUser)) {
        return Result::Error('原手机号不正确或手机号不属于当前用户');
      }
      if ($data['current'] == 'change_phone_old' && $hasUser['id'] != $this->uid) {
        return Result::Error('原手机号不正确或手机号不属于当前用户');
      }
      if ($data['current'] == 'change_phone_new' && !empty($hasUser)) {
        return Result::Error('新手机号已被使用，请更换其他手机号');
      }
      $sms_code = $this->redis->get('smsCode:' . $data['phone']);
      if (empty($sms_code) || ($sms_code != $data['captcha'])) {
        return Result::Error('验证码已过期或不存在，请重新获取！');
      }
      $this->redis->del('smsCode:' . $data['phone']);
      if ($data['current'] == 'change_phone_new') {
        $update['phone'] = $data['phone'];
        Manager::where('id', $this->uid)->update($update);
      }
      return Result::Success();
    }
    return Result::Error('请求不正常');
  }
  public function bind_oauth()
  {
    if (request()->isPost()) {
      $rule = [
        'type' => 'require',
        'code' => 'require',
      ];
      $data = [
        'type'  => input('param.type', '', 'trim'),
        'code'  => input('param.code', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Error($validate->getError());
      }
      if ($data['type'] == 'wx_bind') {
        $bindData = self::wechat_oauth($data['code']);
      } elseif ($data['type'] == 'ww_bind') {
        $bindData = self::ww_oauth($data['code']);
      }
      Manager::where('id', $this->uid)->update($bindData);
      return Result::Success();
    }
    return Result::Error('请求不正常');
  }
  public function get_wechat_bind_qrcode()
  {
    $data = getWxQrcode('ldp_bind::' . $this->uid);
    if (empty($data)) {
      return json(['code' => -1, 'msg' => '二维码获取失败']);
    }
    $return['qrcode'] = $data['qrcode_pic'];
    $return['url'] = $data['url'];
    return json(['code' => 200, 'msg' => 'success', 'data' => $return]);
  }
  public function getWxBindStatus()
  {
    if (empty($this->user['wechat_open_id'])) {
      return json(['code' => 200, 'msg' => '等待扫描', 'cd' => 0]);
    }else{
      return json(['code' => 200, 'msg' => '绑定成功', 'cd' => 200]);
    }
  }
  private static function wechat_oauth($code)
  {
    $wechat_setting = SysSetting::where('id', 1)->find();
    $accessUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $wechat_setting['wechat_appid'] . '&secret=' . $wechat_setting['wechat_secret'] . '&code=' . $code . '&grant_type=authorization_code';
    $http = new HttpRequest;
    $getAccessToken = $http->get($accessUrl);
    $data = json_decode($getAccessToken->body(), true);
    if (isset($data['errmsg'])) {
      throw new ApiException('微信绑定：获取access_token失败 Msg:' . $data['errmsg']);
    }
    $infoUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['access_token'] . '&openid=' . $data['openid'];
    $getAccessToken = $http->get($infoUrl);
    $data = json_decode($getAccessToken->body(), true);
    if (isset($data['errmsg'])) {
      throw new ApiException('微信绑定：获取用户信息失败 Msg:' . $data['errmsg']);
    }
    if (isset($data['unionid']) && !empty($data['unionid'])) {
      $hasUser = Manager::field('id')->where('wechat_union_id', $data['unionid'])->find();
    } else {
      $hasUser = Manager::field('id')->where('wechat_open_id', $data['openid'])->find();
    }
    if (!empty($hasUser)) {
      throw new ApiException('微信绑定：绑定失败，原因：此用户已绑定过帐号');
    }
    $return['wechat_union_id'] = isset($data['unionid']) ? $data['unionid'] : '';
    $return['wechat_open_id'] = isset($data['openid']) ? $data['openid'] : '';
    $return['wechat_nickname'] = isset($data['nickname']) ? $data['nickname'] : '';
    return $return;
  }
  private static function ww_oauth($code)
  {
    $data = (new Wwork)->getUserInfo($code);
    $hasUser = Manager::field('id,salt,password,phone,login_times,is_admin,groupId,status,username,avatar')->where('ww_user_id', $data['UserId'])->find();
    if (!empty($hasUser)) {
      throw new ApiException('微信绑定：绑定失败，原因：此用户已绑定过帐号');
    }
    $return['ww_user_id'] = isset($data['UserId']) ? $data['UserId'] : '';
    return $return;
  }
  public function lock_login()
  {
    if (request()->isPost()) {
      $ip = get_client_ip();
      $rule = [
        'password|密码' => 'require|min:8|max:26',
      ];
      $data = [
        'password'  => input('param.password/s', '', 'trim'),
      ];
      $validate = Validate::rule($rule);
      $result   = $validate->check($data);
      if (!$result) {
        return Result::Error($validate->getError());
      }
      $hasUser = Manager::field('salt,password,status')->where('id', $this->uid)->find();
      if (empty($hasUser)) {
        return Result::Error('登录已过期，请重新登录', -2);
      }
      if ($hasUser['status'] != 1) {
        return Result::Error('用户状态异常或被封禁，请联系上级管理进行处理。');
      }
      $saltPassword = md5($data['password'] . $hasUser['salt']);
      if ($saltPassword != $hasUser['password']) {
        return Result::Error('帐号或密码不正确，请确认后重新登录');
      }
      return Result::Success();
    }
    return Result::Error('请求不正常');
  }
}
